package com.sam.im.heiqun.uis.activities;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.MyCircleItem;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.MycircleAdapter;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.ImageCropViewActivity;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.google.gson.Gson;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.soundcloud.android.crop.Crop;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import com.sam.im.heiqun.utils.StringUtils;
import com.yuyh.library.utils.log.LogUtils;

import static com.soundcloud.android.crop.Crop.REQUEST_CROP;

public class MycircleActivty extends BaseSwipeBackActivity {

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.recyclerView)
    SuperRecyclerView recyclerView;
    @BindView(R.id.nocircle)
    LinearLayout nocircle;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.ok)
    TextView ok;
    @BindView(R.id.time)
    TextView time;
    private PGService pgservice;
    private MycircleAdapter adapter;
    private SwipeRefreshLayout.OnRefreshListener refreshListener;
    private String frienid;
    private PopupMenu popupMenu; // 消息弹框菜单
    private Menu menu;
    private boolean isMycircle = false ;
    public final  static  int CHOSE_IMG = 101 ;
    private String chosepath;

    @Override
    public int getContentViewId() {
        return R.layout.activity_circle;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.my_album);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
//        EventBus.getDefault().register(this);
//        Log.i("wgdinfo", "onRefresh: -----加载加载-----04-----");
        time.setVisibility(View.GONE);
        adapter = new MycircleAdapter(this);
        recyclerView.setAdapter(adapter);
        /*right.setVisibility(View.VISIBLE);
        right.setImageResource(R.drawable.mycircle_item);*/
        ok.setText(getResources().getString(R.string.message));
        ok.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        frienid = getIntent().getStringExtra("frienid");
        final String username = getIntent().getStringExtra("name");
        final String headurl = getIntent().getStringExtra("head");
        refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {//这里执行加载刷新
//                Log.i("wgdinfo", "onRefresh: -----加载加载-----01-----frienid="+frienid);
                if (frienid != null && !frienid.equals(ToolsUtils.getMyUserId())) {
//                    Log.i("wgdinfo", "onRefresh: -----加载加载-----02-----");
                    long l = Long.parseLong(frienid);
                    ImFriendEntivity myFriendForId = ToolsUtils.getMyFriendForId(l);
                    if (myFriendForId != null) {
                        preTvTitle.setText(username + getResources().getString(R.string.de_album));
                        adapter.setFriendname(username, headurl, frienid);
                        inidata(frienid);
                    } else {
                        preTvTitle.setText(username + getResources().getString(R.string.de_album));
                        adapter.setFriendname(username, headurl, frienid);
                        initfriendData(frienid);
                    }
                    getfeedback(frienid);
                    ok.setVisibility(View.GONE);
                    ok.setEnabled(false);
                } else {
//                    Log.i("wgdinfo", "onRefresh: -----加载加载-----03-----");
                    isMycircle = true ;
                    adapter.setFriendname("", "", ToolsUtils.getMyUserId());
                    try {
                        adapter.setShowGift(true);
                        adapter.notifyItemChanged(0);
                    }catch (Exception e){e.printStackTrace();}

                    inidata(ToolsUtils.getMyUserId());
                    UserEntivity user = ToolsUtils.getUser();
                    if (user != null) {
                        Log.i("info","img=="+user.getFeedBackImage());
                        if (user.getFeedBackImage() != null&&!StringUtils.isEmpty(user.getFeedBackImage())) {
                            adapter.setBackgroudUrl(user.getFeedBackImage());
                        }
                    }
                }
                // recyclerView.removeMoreListener();
                //recyclerView.hideProgress();
            }
        };
        recyclerView.setRefreshListener(refreshListener);
        recyclerView.getSwipeToRefresh().post(new Runnable() {
            @Override
            public void run() {
                recyclerView.setRefreshing(true);//执行下拉刷新的动画
                refreshListener.onRefresh();//执行数据加载操作
            }
        });
        /*recyclerView.setupMoreListener(new OnMoreListener() {
            @Override
            public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {

            }
        },1);*/
        pgservice = PGService.getInstance();

        adapter.setOnbackgroudClickListenler(new MycircleAdapter.OnbackgroudClickListenler() {
            @Override
            public void backgroudclick(View view,int type) {
                switch (type){
                    case 0:
                        if (isMycircle)
                            initMenu(view);
                        break;
                    case 1:
                            Intent intent = new Intent(MycircleActivty.this, FriendDetailActivity.class);
                            intent.putExtra("type", 0);
                            if (frienid != null&& !com.yuyh.library.utils.StringUtils.isEmpty(frienid)) {
                                intent.putExtra("id", Long.parseLong(frienid));
                            }else {
                                intent.putExtra("id",Long.parseLong(ToolsUtils.getMyUserId()));
                            }
                            startActivity(intent);
                        break;
                    case 2 :// 礼物列表
                        startActivity(GiftListActivity.class);
                        break;
                    case 3 :// 发布
                        Dialog dialog = MyDialog.ShowDialog(MycircleActivty.this, "", new String[]{getResources().getString(R.string.circle_txt), getResources().getString(R.string.circle_image), getResources().getString(R.string.circle_vedio)}, new MyDialog.DialogItemClickListener() {
                            @Override
                            public void confirm(String result) {
                                if (getResources().getString(R.string.circle_txt).equals(result)){
                                    SendCircleActivity.start(MycircleActivty.this, 1);
                                }else if (getResources().getString(R.string.circle_image).equals(result)){
                                    startActivity(new Intent(MycircleActivty.this,SendCircleActivity.class));
                                }else if (getResources().getString(R.string.circle_vedio).equals(result)){
                                    SendCircleActivity.start(MycircleActivty.this, 2);
                                }
                            }
                        });
                        dialog.show();
                        break;
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getsendmsg(String even){
        if (even.equals("发布成功") ){
            inidata(ToolsUtils.getMyUserId());
        }
    }

    private void getfeedback(String frienid) {
        pgservice.getfriendcircleback(frienid).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(String s) {
                if (s != null) {
                    adapter.setBackgroudUrl(s);
                }
            }
        });
    }

    public void initMenu(View view) {
        popupMenu = new PopupMenu(this, view);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu_collects, menu);
        MenuItem item = menu.getItem(0);
        item.setTitle(getResources().getString(R.string.update_album_fm)); //这里对消息进行判断  是否可以撤回
        popupMenu.show();
        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId()==R.id.delete){//更换相册封面
                    PhotoPickerIntent pt = new PhotoPickerIntent(MycircleActivty.this);
                    pt.setSelectModel(SelectModel.MULTI);
                    pt.setShowCarema(true); // 是否显示拍照， 默认false
                    pt.setMaxTotal(1); // 最多选择照片数量，默认为9
                    //pt.setImageConfig(conFig);
                    startActivityForResult(pt,CHOSE_IMG);
                }
                return false;
            }
        });


    }
    private Uri newUri;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            Log.i("info", requestCode + "====" + resultCode);
            switch (requestCode) {
                case CHOSE_IMG:
                    if (resultCode==RESULT_OK){
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size() > 0) {
                        chosepath = stringArrayListExtra.get(0);
                        Log.i("info", "返回的路径s==" + chosepath);
                        final File file = new File(chosepath);
                        if (file.exists()) {
                            Uri uri = Uri.fromFile(file);
//                            ToolsUtils.cropImageUri(this,uri,800,400,3333);
                      //      ImageCropViewActivity.start(this,chosepath,800,400,3333);

                            newUri  =  Uri.fromFile(new File( getCacheDir(), "cropped"+System.currentTimeMillis()));

                            Crop.of(uri, newUri).asSquare().start(this);

                        } else {
                            ToolsUtils.showToast(MycircleActivty.this, getResources().getString(R.string.file_no));
                        }

                    }
                    }
                    break;
                //新换的图片裁剪
                case REQUEST_CROP:

                    LogUtils.d("图片裁剪uri11:"+Crop.getOutput(data));
                    LogUtils.d("图片裁剪uri22:"+newUri);
                 /*   try {
                        //     GlideUtils.loadHeadCircularImage(this, choesimgpath, headImg);
                        headImg.setImageURI(Crop.getOutput(data));

//                        Bitmap bitmap = PictureUtil.getBitmapFormUri(this, uri);
//                        headImgFile = bitmapToFile(bitmap);
                        photoFile = new File(choesimgpath);
                        // photoFile=ToolsUtils.getFileByUri(newUri,this);
                        haveImg = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }*/

                    if (chosepath != null) {
                        adapter.setBackgroudUrl(chosepath);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String s1 = HttpAssist.uploadFile(new File(chosepath), "", false);
                                Log.i("info", "s1==" + s1);
                                try {
                                    ImageEntity imageEntity = new Gson().fromJson(s1, ImageEntity.class);
                                    EventBus.getDefault().post(imageEntity.getData().getInfo().get(0));
                                } catch (Exception e) {

                                }

                            }
                        }).start();
                    }
                    break;
                case 3333:
                    if (chosepath != null) {
                        adapter.setBackgroudUrl(chosepath);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String s1 = HttpAssist.uploadFile(new File(chosepath), "", false);
                                Log.i("info", "s1==" + s1);
                                try {
                                    ImageEntity imageEntity = new Gson().fromJson(s1, ImageEntity.class);
                                    EventBus.getDefault().post(imageEntity.getData().getInfo().get(0));
                                } catch (Exception e) {

                                }

                            }
                        }).start();
                    }

                    break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initfriendData(String frienid) {
        pgservice.getfriendcircle("1", frienid).subscribe(new AbsAPICallback<MyCircleItem>() {
            @Override
            protected void onResultError(ApiException ex) {
                recyclerView.removeMoreListener();
                recyclerView.hideProgress();
                recyclerView.hideMoreProgress();
            }

            @Override
            public void onNext(MyCircleItem myCircleItem) {
                if (myCircleItem != null) {
                    if (myCircleItem.getList().size() == 0) {
                        nocircle.setVisibility(View.VISIBLE);
                    } else {
                        nocircle.setVisibility(View.GONE);
                        //  Log.i("info","data=="+myCircleItem.toString());
                        adapter.setDatas(myCircleItem.getList());
                        adapter.notifyDataSetChanged();
                    }
                }
                recyclerView.removeMoreListener();
                recyclerView.hideProgress();
                recyclerView.hideMoreProgress();
            }
        });
    }

    private void inidata(String frienid) {

        pgservice.getmycircle("1", frienid).subscribe(new AbsAPICallback<MyCircleItem>() {
            @Override
            protected void onResultError(ApiException ex) {
                nocircle.setVisibility(View.VISIBLE);
                recyclerView.removeMoreListener();
                recyclerView.hideProgress();
                recyclerView.hideMoreProgress();
                MyCircleItem.ListBean listBean = new MyCircleItem.ListBean();
                listBean.setLId("-1");
                listBean.setCreateTime(""+System.currentTimeMillis());
                List<MyCircleItem.ListBean> cirListBeans = new ArrayList<MyCircleItem.ListBean>();
                if (isMycircle)cirListBeans.add(listBean);
                adapter.setDatas(cirListBeans);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onNext(MyCircleItem myCircleItem) {
                if (myCircleItem != null) {
                    if (myCircleItem.getList().size() == 0) {
                        nocircle.setVisibility(View.VISIBLE);
                        recyclerView.removeMoreListener();
                        recyclerView.hideProgress();
                        recyclerView.hideMoreProgress();
                        MyCircleItem.ListBean listBean = new MyCircleItem.ListBean();
                        listBean.setLId("-1");
                        listBean.setCreateTime(""+System.currentTimeMillis());
                        List<MyCircleItem.ListBean> cirListBeans = new ArrayList<MyCircleItem.ListBean>();
                        if (isMycircle)cirListBeans.add(listBean);
                        adapter.setDatas(cirListBeans);
                        adapter.notifyDataSetChanged();
                    } else {
                        nocircle.setVisibility(View.GONE);
                        //  Log.i("info","data=="+myCircleItem.toString());

                        MyCircleItem.ListBean listBean = new MyCircleItem.ListBean();
                        listBean.setLId("-1");
                        listBean.setCreateTime(""+System.currentTimeMillis());
                        List<MyCircleItem.ListBean> cirListBeans = new ArrayList<MyCircleItem.ListBean>();
                        if (isMycircle)cirListBeans.add(listBean);
                        cirListBeans.addAll(myCircleItem.getList());
                        adapter.setDatas(cirListBeans);
//                        adapter.setDatas(myCircleItem.getList());

                        adapter.notifyDataSetChanged();
                    }
                }
                Log.i("info", "执行到这里");
                recyclerView.removeMoreListener();
                recyclerView.hideProgress();
                recyclerView.hideMoreProgress();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getDeletiss(final String s) {
        if (s.contains("http")) {//图片上传完毕
            PGService.getInstance().setcircleback(s, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                @Override
                protected void onResultError(ApiException ex) {
                   // ToolsUtils.showToast(MycircleActivty.this, "修改失败");
                }

                @Override
                public void onNext(ValidateEntivity validateEntivity) {
                    if (validateEntivity != null) {
                       // ToolsUtils.showToast(MycircleActivty.this, validateEntivity.getInfo());
                        UserEntivity user = ToolsUtils.getUser();
                        if (user != null) {
                            user.setFeedBackImage(s);
                            user.save();
                        }
                        //adapter.setBackgroudUrl(s);
                    }
                }
            });

        } else {
            List<MyCircleItem.ListBean> datas = adapter.getDatas();
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).getFeedId().equals(s)) {
                    datas.remove(i);
                    adapter.notifyDataSetChanged();
                }
            }
        }


       /* if (s.equals(getString(R.string.thecricledelete))){
            if (frienid !=null&&!frienid.equals(ToolsUtils.getMyUserId())){
                long l = Long.parseLong(frienid);
                ImFriendEntivity myFriendForId = ToolsUtils.getMyFriendForId(l);
                if (myFriendForId != null) {
                    inidata(frienid);
                }else {
                    initfriendData(frienid);
                }
            }else {
                inidata(ToolsUtils.getMyUserId());
            }
        }*/
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @OnClick({R.id.pre_v_back, R.id.right,R.id.ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.right:

                break;
            case R.id.ok:
                Bundle bundle = new Bundle();
                bundle.putString("key","mycircle");
                startActivity(CircleDetailActivity.class,bundle);
                finish();
                break;
        }
    }


}
